//
//  Status.swift
//  weibo_swift
//
//  Created by dulinlong on 15/7/4.
//  Copyright © 2015年 sheji_56. All rights reserved.
//

import UIKit
import SDWebImage

private let WB_Home_TimeLine = "2/statuses/home_timeline.json"
class Status: NSObject {
    
    //微博创建时间
    var created_at:String?
    // 微博ID
    var id:Int = 0
    //微博信息内容
    var text:String?
    //微博来源
    var source:String?
    //微博配图
    var pic_urls:[[String:String]]?  {
        didSet{
           
        imageUrls = [NSURL]()
            for dict in pic_urls!{
                imageUrls?.append(NSURL(string: dict["thumbnail_pic"]!)!)
            }
        }
    }
    //图片缓存
    private var imageUrls:[NSURL]?
    
    //配图
    var picUrls:[NSURL]? {
         return retweeted_status != nil ? retweeted_status?.imageUrls : imageUrls
    }
    //用户模型
    var user:User?
    /// 被转发的原微博信息字段，当该微博为转发微博时返回
    var retweeted_status: Status?

    
    let properties = ["created_at","id","text","source","pic_urls","user","retweeted_status"]
    
    //字典转模型函数
    init(dict:[String:AnyObject]){
        super.init()
        
        for key in properties{
            if dict[key] == nil || key == "user" || key == "retweeted_status"{
                continue
            }
            setValue(dict[key], forKey: key)
        }
        //字典是剖包含user
        if let userDict = dict["user"] as? [String:AnyObject]{
            user = User(dict: userDict)
        }
        
        //字典是否包含 retweeted_status
        if let retweetDict = dict["retweeted_status"] as? [String:AnyObject]{
            retweeted_status = Status(dict: retweetDict)
        }
    }
    
    override  var description: String {
        let dict = dictionaryWithValuesForKeys(properties)
        
        return "\(dict)"
    }

    
    /// 从网络加载数据
    class func loadData(since_id: Int, max_id: Int, finished:(statuses: [Status]?, error: NSError?) -> ()) {

        var parameters = ["access_token" : sharedUserAccount!.access_token]
        
        if since_id > 0 {
                parameters["since_id"] = "\(since_id)"
        }
        
        if max_id > 0 {
            parameters["since_id"] = "0"
            parameters["max_id"] = "\(max_id - 1)"
        }
        
        NetWorkTool.sharedNetWorkTool().GET(WB_Home_TimeLine, parameters: parameters, success: { (_, JSON) -> Void in
            if let array = JSON["statuses"] as? [[String:AnyObject]]
            {
                //1.获得微博的模型数组
                let list = statuses(array)
                
                //2.缓存图片
                imageCache(list, finished:finished)
        
            } else {
                finished(statuses: nil, error: nil)
            }
            }) { (_, error) -> Void in
                print(error)
                finished(statuses: nil, error: error)
        }
    }
    
    private class func imageCache(statuses:[Status], finished:(statuses: [Status]?, error: NSError?) -> ()){
        
        let group = dispatch_group_create()

        for status in statuses{

            if status.picUrls == nil || status.picUrls!.isEmpty {
                continue
            }
            
            //缓存图片
            for imageUrl in status.picUrls! {
                
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(imageUrl, options: SDWebImageOptions(rawValue: 0), progress: nil, completed: { (_, error, _, _, _) -> Void in
                        dispatch_group_leave(group)
                })
            }
        }
        
        //监听群组调度执行
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in

            //完成回调
            finished(statuses: statuses, error: nil)
        }
    }
        
    
    
    //根据网络传入的数组,完成到模型数组的转换
   private class func statuses (array:[[String:AnyObject]]) -> [Status] {
        
        var StatusM = [Status]()
        
        for dict in array{
            StatusM.append(Status(dict: dict))
        }
        
        return StatusM
    }
    
    
}
